package cn.cool.domain.activity.service.discount;


import cn.cool.domain.activity.adapter.repository.IActivityRepository;
import cn.cool.domain.activity.model.valobj.DiscountTypeEnum;
import cn.cool.domain.activity.model.valobj.GroupBuyActivityDiscountVO;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Slf4j
public abstract class AbstractDiscountCalculateService implements IDiscountCalculateService {

    @Resource
    private IActivityRepository repository;

    @Override
    public BigDecimal calculate(String userId, BigDecimal originalPrice, GroupBuyActivityDiscountVO.GroupBuyDiscount groupBuyDiscount) {
        if (DiscountTypeEnum.TAG.equals(groupBuyDiscount.getDiscountType())) {
            // RQ_KJHKL98UU78H66554GFDV -> userId
            boolean isCrowRange = filterTagId(userId, groupBuyDiscount.getTagId());
            if (!isCrowRange) {
                log.info("【人群标签】折扣优惠计算拦截，userId: {}", userId);
                return originalPrice;
            }
        }

        BigDecimal deductionPrice = doCalculate(userId, originalPrice, groupBuyDiscount);
        if (deductionPrice.compareTo(BigDecimal.ZERO) <= 0) {
            return new BigDecimal("0.01");
        }
        return deductionPrice;
    }

    /**
     * 真正做优惠计算
     * @param userId
     * @param originalPrice
     * @param groupBuyDiscount
     * @return
     */
    protected abstract BigDecimal doCalculate(String userId, BigDecimal originalPrice, GroupBuyActivityDiscountVO.GroupBuyDiscount groupBuyDiscount);

    private boolean filterTagId(String userId, String tagId) {
        return repository.isTagCrowdRange(tagId, userId);
    }
}
